package com.mxnet.chongjin.nci.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mxnet.chongjin.nci.R;
import com.mxnet.chongjin.nci.base.BaseActivity;
import com.mxnet.chongjin.nci.bean.Inspection;
import com.mxnet.chongjin.nci.config.Api;
import com.mxnet.chongjin.nci.receiver.HoneywellReceiver;
import com.mxnet.chongjin.nci.utils.StringUtils;
import com.mxnet.chongjin.nci.view.ItemInspectionView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class InspectionActivity extends BaseActivity implements HoneywellReceiver.OnReceiveCode {
    private Context mContext;
    private Button mButtonView, mButtonQuit, mButtonSave, mButtonAdd;
    private LinearLayout mLinearLayout;
    private TextView mTextViewSum, mTextViewBarcode, mTextViewScanResult;
    private EditText mTextViewLot;
    private List<ItemInspectionView> mViewList;
    private List<Inspection> mList;
    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;

    private HoneywellReceiver mHoneywellReceiver = new HoneywellReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            if ((HoneywellReceiver.INTENT_SCAN_ACTION).equals(intent.getAction())) {
                String data = StringUtils.replaceBlank(intent.getStringExtra("data"));
                if (!TextUtils.isEmpty(data)) {
                    if (data.length() == 6) {
                        //mTextViewLot.setText(data);  //批号
                        if (mViewList.size() > 0) {
                            ItemInspectionView view = mViewList.get(mViewList.size() - 1);
                            view.getEditText1().setText(data);
                        }
                        mTextViewScanResult.setText("批号扫描成功");
                        mTextViewScanResult.setTextColor(Color.GREEN);
                    } else if (data.length() == 8) {
                        mTextViewBarcode.setText(data);  //条码
                        mTextViewScanResult.setText("扫描成功");
                        mTextViewScanResult.setTextColor(Color.GREEN);
                    }

                } else {
                    mTextViewScanResult.setText("扫描异常");
                    mTextViewScanResult.setTextColor(Color.RED);
                    mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                    StringUtils.beep(mContext);
                }
            }
        }
    };

    @Override
    public void notifyThread(Intent intent) {
        String barcode = StringUtils.replaceBlank(intent.getStringExtra("data"));
        if (barcode != null && barcode.length() != 8)
            return;

        OkHttpUtils.get()
                .url(mPreferences.getString("URL_HEADER", "") + Api.BARCODE_QUERY_LOT)
                .addParams("barcode", barcode)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("*****onError", e.getMessage());
                        mTextViewScanResult.setText(e.getMessage());
                        mTextViewScanResult.setTextColor(Color.RED);
                        mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                        StringUtils.beep(mContext);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                if (isSuccess) {
                                    mTextViewLot.setText(jsonObject.optJSONObject("data").optString("lot"));
                                } else {
                                    mTextViewScanResult.setText(jsonObject.optString("message"));
                                    mTextViewScanResult.setTextColor(Color.RED);
                                    mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                StringUtils.beep(mContext);
                            }

                        }
                    }
                });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int i = 0;
                    for (ItemInspectionView inspectionView : mViewList) {
                        if (!TextUtils.isEmpty(inspectionView.getEditText2().getText().toString())) {
                            i += Integer.parseInt(inspectionView.getEditText2().getText().toString());
                        }
                    }
                    mTextViewSum.setText(i + "");
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mHoneywellReceiver, new IntentFilter(HoneywellReceiver.INTENT_SCAN_ACTION));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inspection);
        mContext = InspectionActivity.this;
        mPreferences = getSharedPreferences("nci", MODE_PRIVATE);
        mEditor = mPreferences.edit();

        mHoneywellReceiver.setOnReceiveCode(this);

        mViewList = new ArrayList<>();
        mList = new ArrayList<>();

        mLinearLayout = findViewById(R.id.ll_inspection_for_scroll);

        mTextViewSum = findViewById(R.id.textview_inspection_sum);

        mTextViewLot = findViewById(R.id.textview_inspection_lot);

        mTextViewBarcode = findViewById(R.id.textview_inspection_barcode);

        mTextViewScanResult = findViewById(R.id.textview_inspection_scan_result);

        mButtonView = findViewById(R.id.btn_inspection_view);
        mButtonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mTextViewLot.getText())) {
                    Toast.makeText(mContext, "批号为空！", Toast.LENGTH_SHORT).show();
                } else {
                    mList.clear();
                    for (int i = 0; i < mViewList.size(); i++) {
                        Inspection inspection = new Inspection();
                        inspection.setLocationCode(mViewList.get(i).getEditText1().getText().toString());
                        inspection.setLot(mTextViewLot.getText().toString());
                        inspection.setInQty(Integer.parseInt(mViewList.get(i).getEditText2().getText().toString()));
                        inspection.setChecked(false);
                        inspection.setInUserName(mPreferences.getString("username", ""));
                        inspection.setInDeviceNo(mPreferences.getString("deviceNo", ""));
                        mList.add(inspection);
                    }
                    Intent intent = new Intent(mContext, InspectionCheckActivity.class);
                    intent.putExtra("inspectionData", (Serializable) mList);
                    intent.putExtra("lot", mTextViewLot.getText().toString());
                    startActivity(intent);
                }
            }
        });

        mButtonQuit = findViewById(R.id.btn_inspection_quit);
        mButtonQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, IndexActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        mButtonSave = findViewById(R.id.btn_inspection_save);
        mButtonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 预入库
                if (TextUtils.isEmpty(mTextViewLot.getText())) {
                    Toast.makeText(mContext, "批号为空！", Toast.LENGTH_SHORT).show();
                } else {
                    if (mViewList.size() > 0) {
                        mList.clear();
                        for (int i = 0; i < mViewList.size(); i++) {
                            Inspection inspection = new Inspection();
                            inspection.setLocationCode(mViewList.get(i).getEditText1().getText().toString());
                            inspection.setLot(mTextViewLot.getText().toString());
                            inspection.setCheckQty(Integer.parseInt(mViewList.get(i).getEditText2().getText().toString()));
                            //inspection.setInQty(0);
                            inspection.setChecked(false);
                            inspection.setInUserName(mPreferences.getString("username", ""));
                            inspection.setInDeviceNo(mPreferences.getString("deviceNo", ""));
                            mList.add(inspection);
                        }
                        OkHttpUtils.post()
                                .url(mPreferences.getString("URL_HEADER", "") + Api.INSPECTION)
                                .addParams("data", new Gson().toJson(mList))
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        Log.i("*****==mButtonSave==", e.getMessage());
                                        mTextViewScanResult.setText(e.getMessage());
                                        mTextViewScanResult.setTextColor(Color.RED);
                                        mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        if (!TextUtils.isEmpty(response)) {
                                            try {
                                                JSONObject jsonObject = new JSONObject(response);
                                                boolean isSuccess = jsonObject.optBoolean("success");
                                                if (isSuccess) {
                                                    Toast.makeText(mContext, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                                                    Intent intent = new Intent(mContext, IndexActivity.class);
                                                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                                    startActivity(intent);
                                                    finish();
                                                } else {
                                                    mTextViewScanResult.setText(jsonObject.optString("message"));
                                                    mTextViewScanResult.setTextColor(Color.RED);
                                                    mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });
                    } else {
                        Toast.makeText(mContext, "没有数据！", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        mButtonAdd = findViewById(R.id.btn_inspection_add);
        mButtonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击新增，添加一条记录
                ItemInspectionView view = new ItemInspectionView(mContext, R.layout.item_inspection);
                Button button = view.getButton();
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 点击删除，去掉一条记录
                        ItemInspectionView view1 = (ItemInspectionView) v.getParent().getParent();
                        mViewList.remove(view1);
                        mLinearLayout.removeView(view1);
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                });
                EditText editText2 = view.getEditText2();
                editText2.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                });
                mViewList.add(view);
                mLinearLayout.addView(view, 0);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mHoneywellReceiver);
    }
}
